package com.google.code.sysarch.v2.v2_final;

import java.awt.Graphics2D;

public class Santa extends Thread implements Drawable {
	
	private Sprite sprite;
	private PathWalker myWalker;
	private int offset_x;
	private int offset_y;
	private long thread_timer = 0;
	private boolean running;
	private int awake;
	private boolean sleepNextCycle;
	
	Santa(String filename) {
		this.sprite = SpritePool.get().getSprite(filename);
		this.awake = 5;
		this.sleepNextCycle = true;
	}

	/**
	 * creates the one and only Santa Claus
	 */	
	public void run() {
		thread_timer = System.nanoTime();
		running = true;
		double delta;
		myWalker = Game.get().getMap().getPathWalker(this);		
		
		while (this.running) {	
			if (sleepNextCycle) {
				synchronized (Game.monitor) {							
					try {
						awake = 0;
						Game.monitor.notifyAll();
						Game.monitor.wait();
					} catch (InterruptedException e) {}
					Game.get().getMap().move(myWalker, "SantaFrontDoor");
					this.sleepNextCycle = false;
					thread_timer = System.nanoTime();
				}
			}
			delta = (double)(System.nanoTime() - thread_timer) / 1000000000L;			
			Game.get().getMap().updateSingle(myWalker, delta);
			thread_timer = System.nanoTime();				
			try {
				sleep(30);
			} catch (InterruptedException e) { }
		}
	}
	
	public void setOffset(int x, int y) {
		this.offset_x = x;
		this.offset_y = y;
	}
	
	public void draw(Graphics2D g, int x, int y) {
		this.sprite.draw(g, x+offset_x, y+offset_y);		
	}
	
	public void kill() {
		this.running = false;
	}
	
	public String toString() {
		return "Santa";
	}	
	
	public boolean isSleeping() {
		return awake > 0 ? false : true;
	}
	
	public void wakeUp(String faction) {
		if (faction.equals("Reindeer")) {
			awake = 1;
		} else if (faction.equals("Elves")) {
			awake = 2;
		}
	}
	
	public boolean onEvent(PathWalker p, String event, WayPoint caller, WayPoint helper) {
		if (event.equals("repair")) {
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) { }
			Game.get().getMap().move(p, "FabrikTor");
			return true;
		} else if (event.equals("fly")) {
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) { }
			return true;			
		} else if (event.equals("sleep")) {
			this.sleepNextCycle = true;
		} else if (event.equals("doorstep")) {
			if (helper.getName().equals("SantaHaus") && awake == 2) {
				Game.get().getMap().move(p, "Schnee1");
			} else if (helper.getName().equals("SantaHaus") && awake == 1) {
				Game.get().getMap().move(p, "Schlittenfahrt");
			} else {
				Game.get().getMap().move(p, "SantaHaus");
			}
		} else if (event.equals("gather")) {
			Game.get().getMap().move(p, "SantaFrontDoor");
		} else if (event.equals("gate")) {
			if (helper.getName().equals("Schnee2")) {
				Game.get().getMap().move(p, "FabrikFehler");
			} else {
				Game.get().getMap().move(p, "Schnee3");
			}
		}
		return false;		
	}	
	
}
